package com.richpencil.modules.weixin.rest;

import com.jfinal.weixin.sdk.kit.IpKit;
import com.richpencil.modules.system.rest.BaseController;
import com.richpencil.modules.weixin.domain.UrlEntry;
import com.richpencil.modules.weixin.domain.WxResult;
import com.richpencil.modules.weixin.service.WxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * DemoController
 * TODO
 * rockcode
 * 2018/6/25-9:47
 */
@Controller
public class VueController extends BaseController {

    @Autowired
    com.richpencil.config.ProjectConfigInfo ProjectConfigInfo;
    @Autowired
    WxService wxService;

//
//    @RequestMapping("/")
//    private String index(ModelMap map, HttpServletRequest request, String code, String state) {
//        String url = "redirect:/weixinto";
//        return  url;
//    }


    @RequestMapping("weixinto")
    private String weixinto(ModelMap map, HttpServletRequest request, String code, String state) {
        String url = "/index";
        UrlEntry entry = this.wxService.decodeState(state);
        if(!entry.valid()){
            this.setWxerrorMap(map, "type is error", "", "");
            return url;
        }
        String ip = IpKit.getRealIp(request);
        WxResult wxresult = wxService.getWxResult( code, ip);
        if(!wxresult.success) {
            this.setWxerrorMap(map, wxresult.message, "", "");
            return url;
        }
        entry.fopenid= wxresult.openid;
        map.put("fopenid", "abc");
        return  url;
    }

    @RequestMapping("weixintolocal")
    private String weixintolocal(ModelMap map, HttpServletRequest request, String code, String state) {
        String url = "/index";
        map.put("fopenid", "fopenid001");
            return  url;
    }


    @RequestMapping("weixinscan")
    private String weixinscan(ModelMap map, HttpServletRequest request, String code, String state) {
        String url = "/weixinscan";
        String message = "";
        UrlEntry entry=this.wxService.decodeState(state);
        if(!entry.valid()){
            this.setWxerrorMap(map, "type is error", "", "");
            return url;
        }
        String ip = IpKit.getRealIp(request);
        WxResult wxresult = wxService.getWxResult( code, ip);
        if(!wxresult.success) {
            this.setWxerrorMap(map, wxresult.message, "", "");
            return url;
        }
        entry.fopenid= wxresult.openid;
        return  url;
    }


    @RequestMapping("back")
    private String weixintolocal(ModelMap map, HttpServletRequest request) {
        String url = "/index";
        return  url;
    }


}